package com.excalibur.core.util.xss;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class HtmlCleaner {
	
	/**
	 * 定义script的正则表达式
	 */
	public static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; 
	/**
	 * 定义style的正则表达式
	 */
	public static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; 
	/**
	 * 定义HTML标签的正则表达式
	 */
	public static final String regEx_html = "<[^>]+>";   

	/**
	 * 
	 * @param html
	 * @return
	 */
	public final static String clean(String html){
		
		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);  
        Matcher m_script = p_script.matcher(html);  
        html = m_script.replaceAll(""); // 过滤script标签  
  
        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);  
        Matcher m_style = p_style.matcher(html);  
        html = m_style.replaceAll(""); // 过滤style标签
		
		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);  
        Matcher m_html = p_html.matcher(html);  
        html = m_html.replaceAll(""); // 过滤html标签
		return html;
	}

	/**
	 * 清除script,style标签
	 * @param html
	 * @return
     */
	public final static String cleanScriptStyle(String html){

		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(html);
		html = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(html);
		html = m_style.replaceAll(""); // 过滤style标签
		return html;

	}
	
	/**
	 * 
	 * @param html          需要过滤内容
	 * @param regex         过滤正则
	 * @return
	 */
	public final static String clean(String html, String regex){
		Pattern p_script = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);  
        Matcher m_script = p_script.matcher(html);  
        html = m_script.replaceAll("");
        return html;
	}
	
}
